package com.novellotus.iov.carvice.activity;


import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jakewharton.rxbinding2.view.RxView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.utils.DataSign;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.tbruyelle.rxpermissions2.Permission;

import java.io.File;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 客户确认
 */
public class ConfirmActivity extends BaseActivity {

    @BindView(R.id.tv_tittle)
    TextView tv_tittle;
    @BindView(R.id.rlt_sign)
    RelativeLayout rlt_sign;//没签名布局
    @BindView(R.id.rlt_image_sign)
    RelativeLayout rlt_image_sign;//已经签名布局
    @BindView(R.id.img_sign)
    ImageView img_sign;
    String path = "";

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_confirm);
    }

    @Override
    public void init() {
        tv_tittle.setText("客户确认");
        setClickAutograph(rlt_sign);
    }

    @OnClick(R.id.img_back)
    void back() {
        finish();
    }

    @OnClick(R.id.rlt_image_sign)
    void sign() {
        openForResultActivity(AutographActivity.class);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            isFirst = true;
            path = data.getStringExtra("path");
            Bitmap bitmap = MyUtils.getLocalBitmap(path); //从本地取图
            rlt_sign.setVisibility(View.GONE);
            rlt_image_sign.setVisibility(View.VISIBLE);
            img_sign.setImageBitmap(bitmap);
        }
    }

    /**
     * 设置点击签名按钮
     */
    boolean isFirst = true;

    private void setClickAutograph(View view) {
        RxView.clicks(view)
                .compose(RxSchedulers.lifecycle(this)).throttleFirst(1, TimeUnit.SECONDS)
                .compose(rxPermissions.ensureEach(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS))
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (isFirst) {
                            isFirst = false;
                            if (permission.granted) {
                                openForResultActivity(AutographActivity.class);
                            } else {
                                MyUtils.showToast(ConfirmActivity.this, "文件读写权限已被禁止，请设置允许本应用读写权限，否则不能保存签名");
                            }
                        }

                    }
                });

    }


    @OnClick(R.id.btn_confirm)
    void confirm() {
        saveMessage("fuck");
    }

    /**
     * @param value {fid:'',remark:'',address:'',lat:'',lng:''}
     */
    public void saveMessage(String value) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fid", "EhGZEVpRGWjXtuAFKCxsrw");
        jsonObject.addProperty("remark", "哥弄好了");
        jsonObject.addProperty("address", "皇后大道");
        jsonObject.addProperty("lat", "30.538352");
        jsonObject.addProperty("lng", "104.061682");
        File f = new File(path);
        // create RequestBody instance from file
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), f);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("file", "file.png", requestFile);
        //RequestBody  string
        RequestBody description =
                RequestBody.create(MediaType.parse("multipart/form-data"), DataSign.getSign(jsonObject.toString(), this));


        Observable<BaseEntity<Boolean>> observable = RetrofitFactory.getInstance().confirm(description, body);
        observable.compose(RxSchedulers.<BaseEntity<Boolean>>compose())
                .subscribe(new BaseObserver<Boolean>(this) {
                    @Override
                    public void onSuccess(Boolean response) {
                        MyUtils.showToast(ConfirmActivity.this, "修改信息成功");
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        MyUtils.showToast(ConfirmActivity.this, msg);
                    }

                    @Override
                    public void onError(String msg) {
                        MyUtils.showToast(ConfirmActivity.this, msg);
                    }
                });
    }
}
